﻿using IdentityServer4.Validation;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using System;
using IdentityModel;
using IdentityServer4.Models;
using Newtonsoft.Json;

namespace NETCORE.IdentityServer4.Service
{


    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        public ResourceOwnerPasswordValidator()
        {
        }

        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
            if (context.UserName == "wjk" && context.Password == "123")
            {
                context.Result = new GrantValidationResult(
                 subject: context.UserName,
                authenticationMethod: "custom",
                //authenticationMethod: OidcConstants.AuthenticationMethods.Password,
                claims: GetUserClaims());

                //context.Result = new GrantValidationResult(
                //    JsonConvert.SerializeObject(context.UserName),
                //    OidcConstants.AuthenticationMethods.UserPresenceTest);

            }
            else
            {

                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
        }
        //可以根据需要设置相应的Claim
        private Claim[] GetUserClaims()
        {
            return new Claim[]
            {
            new Claim("userid", 1.ToString()),
            new Claim(JwtClaimTypes.Name,"wjk"),
            new Claim(JwtClaimTypes.GivenName, "ssss"),
            new Claim(JwtClaimTypes.FamilyName, "ddddd"),
            new Claim(JwtClaimTypes.Email, "11111@qq.com"),
            new Claim(JwtClaimTypes.Role,"admin")
            };
        }

    }
}
